import createElement from './createElement.js';
import updateChildren from './updateChildren.js';

// 当前元素可复用，为其打补丁，在旧元素上添加新属性，移除旧属性，再比较子元素
export default function patchVnode(oldVnode, newVnode) {
  // 新旧vnode相同
  if (oldVnode === newVnode) return;
  newVnode.elm = oldVnode.elm;
  // console.log(oldVnode.elm);
  // console.log((newVnode.elm = oldVnode.elm));

  const newElmAttrsList = new Set(); // 新节点有的属性
  Object.keys(newVnode.props).forEach(key => {
    const oldAttr = oldVnode.props[key];
    const newAttr = newVnode.props[key];
    if (oldAttr || oldAttr !== newAttr) {
      newElmAttrsList.add(key);
      oldVnode.elm.setAttribute(key, newAttr);
    }
  });

  Object.keys(oldVnode.props).forEach(key => {
    if (!newElmAttrsList.has(key)) {
      oldVnode.elm.removeAttribute(key);
    }
  });

  if (newVnode.text) {
    // 子节点都为文本且不相同，或者旧节点右多个子节点
    if ((oldVnode.text && oldVnode.text !== newVnode.text) || oldVnode.children) {
      oldVnode.elm.innerText = newVnode.text;
    }
  } else if (newVnode.children) {
    if (oldVnode.text) {
      const frag = document.createDocumentFragment();

      newVnode.children.forEach(cVnode => {
        frag.appendChild(createElement(cVnode));
      });

      oldVnode.elm.innerText = '';
      oldVnode.elm.appendChild(frag);
    } else {
      updateChildren(oldVnode.elm, oldVnode.children, newVnode.children);
    }
  }
}
